package com.apes.scm.masterdata.frame.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.scm.masterdata.area.model.Area;
import com.apes.scm.masterdata.area.repository.AreaRepository;
import com.apes.scm.masterdata.frame.model.ConsignmentRule;
import com.apes.scm.masterdata.frame.model.ConsignmentSpecial;
import com.apes.scm.masterdata.frame.repository.ConsignmentRuleRepository;
import com.apes.scm.masterdata.frame.repository.ConsignmentSpecialRepository;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.Corporate;
import com.apes.scm.masterdata.product.model.Brand;
import com.apes.scm.masterdata.product.model.Category;
import com.apes.scm.masterdata.product.repository.BrandRepository;
import com.apes.scm.masterdata.product.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName : ConsignmentRuleService 
 * @Description : 带安规则业务层  
 * @Author : WSJ 
 * @Date: 2020-02-21 17:50 
 */
@Service("consignmentRuleService")
public class ConsignmentRuleService extends DomainService {
    @Autowired
    private ConsignmentRuleRepository consignmentRuleRepository;
    @Autowired
    private AreaRepository areaRepository;

    public ConsignmentRule save(SimpleRequest request) {
        ConsignmentRule consignmentRule = request.getO(ConsignmentRule.class);
        getCityAndProvince(consignmentRule);
        consignmentRule.setState("create");
        return consignmentRuleRepository.saveAndFlush(consignmentRule);
    }

    /**
     * 获取省市区
     * @param consignmentRule
     */
    private void getCityAndProvince(ConsignmentRule consignmentRule) {
        //获取城市
        Area city = consignmentRule.getCity();
        //获取省份
        String provinceId = city.getParent();
        Area province = areaRepository.findOne(provinceId);
        consignmentRule.setProvince(province);
    }

    public ConsignmentRule update(SimpleRequest request) {
        ConsignmentRule consignmentRule = request.getO(ConsignmentRule.class);
        //获取城市
        getCityAndProvince(consignmentRule);
        consignmentRule.setState("create");
        consignmentRule = consignmentRuleRepository.saveAndFlush(consignmentRule);
        return consignmentRule;
    }


    public ConsignmentRule delete(SimpleRequest request) throws Exception  {
        ConsignmentRule consignmentRule = checkData(request);
        consignmentRule.setState("delete");
        consignmentRule.setDeleteDate(new Date());
        consignmentRule.setDeleteUid(this.getPerson(request));
        return  consignmentRuleRepository.saveAndFlush(consignmentRule);
    }

    public ConsignmentRule approve(SimpleRequest request) throws Exception  {
        ConsignmentRule consignmentRule = checkData(request);
        //需要判断, 是否存在已审核, 的同个配件同个城市 的 带安规则
        List<ConsignmentRule> list = consignmentRuleRepository.findAll(
                JpaDsl.toCriteriaByEq("city",consignmentRule.getCity(),"category",consignmentRule.getCategory(),"state","approve")
        );
        if (list.size() > 0) throw new RuntimeException("该城市已存在该配件的带安规则,单号: "+list.get(0).getId());
        consignmentRule.setState("approve");
        consignmentRule.setApproveDate(new Date());
        consignmentRule.setApproveUid(this.getPerson(request));
        return consignmentRuleRepository.saveAndFlush(consignmentRule);
    }
    public ConsignmentRule repeal(SimpleRequest request) throws Exception  {
        ConsignmentRule consignmentRule = checkData(request);
        consignmentRule.setState("repeal");
        consignmentRule.setRepealDate(new Date());
        consignmentRule.setRepealUid(this.getPerson(request));
        return consignmentRuleRepository.saveAndFlush(consignmentRule);
    }
    private ConsignmentRule checkData(SimpleRequest request) {
        String id = request.get("id");
        int versions = (int) request.get("version");

        ConsignmentRule consignmentRule = consignmentRuleRepository.findOne(id);
        if (consignmentRule == null) throw new RuntimeException("规则【" + id + "】在系统中不存在。");
        if (consignmentRule.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        return consignmentRule;
    }

    /**
     * 导入配件带安规则
     * @param request
     * @return
     */
    public String importConsignmentRule(SimpleRequest request) {
        List<ConsignmentRule> list = request.getA("items",ConsignmentRule.class);
        if (list.size() == 0) throw new RuntimeException("导入数据不能为空!!!");
        list.forEach(
                item -> {
                    item.setState("approve");
                    item.setCreator(getPersonId(request));
                    getCityAndProvince(item);
                    item.setApproveDate(new Date());
                    item.setApproveUid(getPerson(request));
                    item.setCreateDate(new Date());
                    consignmentRuleRepository.saveAndFlush(item);
                }
        );
        return "导入成功!!!";
    }


    /**
     * 查询单个数据
     * @param request
     * @return
     */
    public ConsignmentRule findOne(SimpleRequest request) {
        String id = request.get("ID");

        ConsignmentRule  consignmentRule = consignmentRuleRepository.findOne(id);

        if (consignmentRule == null) throw new RuntimeException("合作类型：" + request.get("id") + " 在系统中不存在。");
        return consignmentRule;
    }

    /**
     * 查询商品的带安规则
     * dept 部门（门店对应公司的城市）
     * category
     * brand 品牌
     * @param request
     * @return
     */
    public List<ConsignmentRule> findAllByCategoryAndProvinceAndCity(SimpleRequest request) {
       List<ConsignmentRule> ruleList = new ArrayList<ConsignmentRule>();
        JSONObject jo = request.getJO();
        if (!jo.containsKey("categoryId") || !jo.containsKey("brandId"))
            throw new RuntimeException("获取带安规则必须传入配件和品牌!!");
        Area province ;
        Area city  ;
        Category category ;
        Brand brand;
        try {
            Corporate corporate = SpringManager.getBean(DeptRepository.class).findOne(jo.getString("deptId")).getCompany().getParty().getCorporate();
            province = corporate.getRegProvince();
            city = corporate.getRegCity();
            if(province == null || city == null) throw new Exception("");
        }catch (Exception e){
            return ruleList;
        }

        try {
            category = SpringManager.getBean(CategoryRepository.class).findOne(jo.getString("categoryId"));
            brand = SpringManager.getBean(BrandRepository.class).findOne(jo.getString("brandId"));
            if(category == null) throw new Exception("");
        }catch (Exception e){
            return ruleList;
        }
        ruleList = consignmentRuleRepository.findAll(
                JpaDsl.toCriteriaByEq("category.id",category.getId(),"province.id",province.getId(),"city.id",city.getId(),"state","approve")
        );
        if (checkConsignmentSpecial(category,brand)) return new ArrayList<ConsignmentRule>(); ;
       return ruleList;
    }

    /**
     * 检查配件对应的是否存在带安特例
     * @param
     * @return
     */
    public boolean checkConsignmentSpecial(Category category,Brand brand) {
        List<ConsignmentSpecial> list = SpringManager.getBean(ConsignmentSpecialRepository.class).findAll(
                JpaDsl.toCriteriaByEq("category",category,"brand",brand)
        ).stream().filter(
                item -> {
                    return item.getDeleteUid() == null;
                }
        ).collect(Collectors.toList());
        if (list.size() >0) return true;
        return  false;
    }
}
